package com.ihisun.tmhcms.core.service.activityservice.impl;

import com.ihisun.tmhcms.core.dao.activitydao.ActivityDao;
import com.ihisun.tmhcms.core.dto.activitydto.ActivityDto;
import com.ihisun.tmhcms.core.service.activityservice.ActivityService;
import com.ihisun.tmhcms.core.vo.ActivityVo;
import com.ihisun.tmhcms.utils.DateUtils;
import com.ihisun.tmhcms.utils.ResponseVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;


@Service
public class ActivityServiceImpl implements ActivityService {
    @Resource
    ActivityDao activityDao;
    @Resource
    EntityManager entityManager;

    @Override
    public ResponseVo editActivity(ActivityDto activityDto) {
        if (activityDto.getId() != null && !"".equals(activityDto.getId())) {
            activityDto.setCreateTime(DateUtils.getCurrentTime());
            activityDto.setUpdateTime(DateUtils.getCurrentTime());
            activityDto.setState(1);
            activityDao.save(activityDto);
        } else {
            activityDto.setUpdateTime(DateUtils.getCurrentTime());
            activityDto.setState(1);
            activityDao.save(activityDto);
        }
        return ResponseVo.ok();
    }

    @Override
    public ResponseVo updateState(String id, Integer state) {
        Optional<ActivityDto> byId = activityDao.findById(Long.parseLong(id));
        ActivityDto activityDto = byId.get();
        activityDto.setState(state);
        activityDto.setUpdateTime(DateUtils.getCurrentTime());
        return ResponseVo.ok(byId);
    }

    @Override
    public ResponseVo SearchActivity(String title, Integer state) {
        StringBuilder sql=new StringBuilder("select * from tb_activity where state!=3");
        if (title!=null&&!"".equals(title)){
           sql.append(" and  title="+title+"");
        }
        if (state!=null){
            sql.append(" and state="+state+"");
        }
        List<ActivityVo> resultList = entityManager.createNativeQuery(sql.toString(), ActivityVo.class).getResultList();
        return ResponseVo.ok(resultList);
    }
}
